package com.example.boot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.boot.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("")
@Api(tags = "jsoncontroller")
public class JsonController {

    //对象转json字符串
    @ApiOperation("testtetset")
    @RequestMapping("/test")
    public String test() {
        User user = new User();
        user.setId(1);
        user.setUserName("张三");
        String s = JSON.toJSONString(user);
        System.out.println(s);
        Map<Object, Object> map = new HashMap<>();
        map.put("id", 2);
        map.put("userName", "张三");
        String s1 = JSONObject.toJSONString(map);
        System.out.println(s1);

        return s;
    }

    //json字符串转对象
    @RequestMapping("/test1")
    public void test1() {
        String s = "{\"id\":1,\"userName\":\"张三\"}";
        User user = JSON.parseObject(s, User.class);
        System.out.println(user.getId() + "," + user.getUserName());
    }

    /**
     *
     * @return
     */
    //JSONObject
    @ResponseBody
    @RequestMapping("/a")
    public User a() {
        User user = new User();
        user.setId(1);
        user.setUserName("test");
        JSONObject.toJSONString(user);
        return user;
    }



}
